package com.qdy.util;

import com.jiai.core.util.SpringUtil;
import com.qdy.config.Config;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * Created by Administrator on 2017/3/26.
 */

public class UploadUtil {
    private static final Logger log= LoggerFactory.getLogger(UploadUtil.class);





    /**
     * 提定上传到正式目录中
     * @param file
     * @return
     */
    public static  String copyFile(MultipartFile file)  {
        String newName="";
        try {
            String filePath = SpringUtil.getBean(Config.class).getSavePath();
            newName=UUID.randomUUID() + getExtName(file.getOriginalFilename(), '.');
             filePath += File.separator + "image" + File.separator + newName;
            if (file.isEmpty()) {
                return null;
            }
            File dest=new File(filePath);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            log.info("file upload susscess [{}]",filePath);
            return newName;
        }catch (Exception e){
            log.info("file upload error [{}]",e.getMessage());
            return null;
        }
    }

    public   static String getExtName(String s, char split) {
        int i = s.indexOf(split);
        int leg = s.length();
        return (i > 0 ? (i + 1) == leg ? " " : s.substring(i, s.length()) : " ");
    }
}
